package com.mesnac.filemgr.entity;

import java.io.File;
import java.util.Date;

import org.apache.commons.io.FileUtils;

/**
 * 文件管理类
 * 
 * @author chilei
 * 
 */
public class FileMgr {

	/**
	 * 上传一个文件
	 * 
	 * @param file
	 * @param uploadFile
	 * @return
	 * @throws Exception
	 */
	public static synchronized boolean uploadFile(FileInfor file,
			File uploadFile) throws Exception {
		File newFile = new File(file.getFilePath());
		FileUtils.copyFile(uploadFile, newFile);
		return true;
	}

	/**
	 * 下载一个文件,暂时没有什么用
	 * 
	 * @param parentPath
	 * @param filename
	 * @return
	 * @throws Exception
	 */
	public static synchronized String download(String parentPath,
			String filename) throws Exception {
		return parentPath + File.separator + filename;
	}

	/**
	 * 删除一个文件
	 * 
	 * @param parentPath
	 * @param filename
	 * @return
	 * @throws Exception
	 */
	public static synchronized boolean delFile(String parentPath,
			String filename) throws Exception {
		String abpath = parentPath + File.separator + filename;
		File a = new File(abpath);
		return a.delete();
	}

	/**
	 * 上传新版本
	 * 
	 * @param file
	 * @param parentPath
	 * @param oldname
	 * @param uploadfile
	 * @throws Exception
	 */
	public static synchronized void updateFile(FileInfor file,
			String parentPath, String oldname, File uploadfile)
			throws Exception {
		// 把原来的文件重命名
		File oldFile = new File(parentPath + File.separator + oldname);
		File newFile = new File(parentPath + File.separator + oldname + "."
				+ new Date());
		oldFile.renameTo(newFile);
		File newf = new File(file.getFilePath());
		FileUtils.copyFile(uploadfile, newf);
	}

	/**
	 * 删除文件夹
	 * 
	 * @param file
	 * @param parentPath
	 * @param oldname
	 * @param uploadfile
	 * @throws Exception
	 */
	public static synchronized void delDir(FileInfor file, String parentPath,
			String oldname, File uploadfile) throws Exception {
		String delpath = parentPath + File.separator + oldname;

		File a = new File(delpath);
		if (!a.isDirectory()) {
			a.delete();
		} else if (a.isDirectory()) {
			String[] filelist = a.list();
			for (int i = 0; i < filelist.length; i++) {
				File delfile = new File(delpath + File.separator + filelist[i]);
				if (!delfile.isDirectory())
					delfile.delete();
				else if (delfile.isDirectory())
					delDir(null, delpath, filelist[i], null);
			}
			a.delete();
		}
	}
}
